<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/11/20
 * Time: 20:39
 */

namespace App\Services\BackendApi;

use App\Handlers\BackendApiResponse;
use App\Services\RedisService;
use App\Services\UploadOSSorStorage;
use Illuminate\Support\Facades\Log;

class CommonService
{
    use RedisService;

    use BackendApiResponse;

    public function __construct()
    {
//        $this->checkSign();
    }

    public function checkSign()
    {
        $request = request();
        if (!isset($request->app_id) || empty($request->app_id)) {
            die(json_encode([
                'code' => 1000000,
                'message' => 'appId不能为空',
            ]));
        }
        if (!isset($request->sign) || empty($request->sign)) {
            die(json_encode([
                'code' => 1000001,
                'message' => '签名不能为空',
            ]));
        }
        $apiKey = config('backendapikey.' . $request->app_id);
        if (empty($apiKey)) {
            die(json_encode([
                'code' => 1000004,
                'message' => 'appKey不存在',
            ]));
        }
        $params = $request->all();
        $clientSign = $params['sign'];
        unset($params['sign']);
        $checkSign = getSign($params, $apiKey);
        Log::info('client_sign' . $clientSign);
        Log::info('check_sign' . $checkSign);
        if ($clientSign !== $checkSign) {
            die(json_encode([
                'code' => 1000003,
                'message' => '签名验证不正确',
            ]));
        }
    }

    /**
     * 上传图片
     * @param $storageType
     * @param $folder
     * @param $file
     * @return bool|\Illuminate\Http\JsonResponse|string
     */
    public function upload($storageType, $folder, $file, $oldFilePath = '')
    {
        $uploadOSSorStorage = new UploadOSSorStorage();
        if (!empty($oldFilePath)) {
            $uploadOSSorStorage->deleteOSSorStorageLocal($oldFilePath, $storageType);
        }
        // 本地文件是否上传成功
        if (!$uploadOSSorStorage->isValidFile($file)) return $this->responseJson(1030000);//无效文件
        //上传文件类型
        if (!$uploadOSSorStorage->isValidFileType($file)) return $this->responseJson(1030001);//图片格式不支持
        //验证文件大小是否超出限制
        $fileLimitSize = config('filesystems.disks.image_size');
        if (!$uploadOSSorStorage->isValidFileSize($file, $fileLimitSize)) return $this->responseJson(1030002);//图片大小超出限制
        $isUpload = $uploadOSSorStorage->uploadOSSorStorageLocalApi($file, $fileLimitSize, $storageType, $folder);
        if (!$isUpload) {
            return $this->responseJson(1030003);//图片上传失败
        }
        return $isUpload;
    }
}